<?php

namespace addons\helper\controller\wxapp;

use addons\helper\controller\wxapp\Base;
use fast\Http;
use think\addons\AddonException;
use think\addons\Service;
use think\Cache;
use think\Config;
use think\Exception;

class Addon extends Base
{
    protected $searchFields = 'title';
    protected $model = null;
    protected $categoryList = [];
    protected $config = [
        'model'             => '插件',
        'limit'             => 10,
        'defaultSort'       => 'id',
        'defaultOrder'      => 'desc',
        'search'            => true,
        'tabField'          => 'category_id',
        'searchPlaceholder' => '输入标题搜索',
        'field' => [
            'name'          => ['标识', 'text', false,  false, '', true, false, false],
            'title'         => ['插件名称', 'text', false,  false, '', true, false, false],
            'intro'         => ['描述', 'text', false,  false, '', true, false, false],
            'description'   => ['介绍', 'text', false,  false, '', true, false, false],
            'image'         => ['图片', 'text', false,  false, '', true, false, false],
            'screenshots'   => ['截图', 'text', false,  false, '', true, false, false],
            'author'        => ['作者', 'text', false,  false, '', true, false, false],
            'url'           => ['链接', 'text', false,  false, '', true, false, false],
            'demourl'       => ['演示地址', 'text', false,  false, '', true, false, false],
            'qq'            => ['作者QQ', 'text', false,  false, '', true, false, false],
            'score'         => ['评分', 'text', false,  false, '', true, false, false],
            'version'       => ['版本', 'text', false,  false, '', true, false, false],
            'price'         => ['价格', 'text', false,  false, '', true, false, false],
            'extendedprice' => ['高级授权价格', 'text', false,  false, '', true, false, false],
            'originalprice' => ['基础授权价格', 'text', false,  false, '', true, false, false],
            'flag'          => ['标志', 'text', false,  false, '', true, false, false],
            'likes'         => ['喜欢', 'text', false,  false, '', true, false, false],
            'downloads'     => ['下载次数', 'text', false,  false, '', true, false, false],
            'require'       => ['系统要求', 'text', false,  false, '', true, false, false],
            'createtime'    => ['创建时间', 'datetime', false,  false, '', true, false, false],
            'releasetime'   => ['更新时间', 'datetime', false,  false, '', true, false, false],
            'releaselist'   => ['更新历史', 'datetime', false,  false, '', true, false, false],

        ],
        'fieldContent' => [
            'category' => [],
            'flag' => [
                'recommend' => '推荐',
                'hot'       => '热门'
            ],
            'status' => [
                'normal' => '正常',
                'hidden' => '隐藏'
            ]
        ],
        'auth' => [
            'state'  => [
                'name' => '状态',
                'url'  => 'addon/state',
            ],
            'config'  => [
                'name' => '配置',
                'url'  => 'addon/config',
            ],
            // operate_bar增加的操作
            'operates' => [
                [
                    'type'  => 'select',
                    'url'   => 'addon/index',
                    'title' => '选择查看',
                    'options' => [
                        [
                            'text'   => '全部',
                            'value'  => 'all',
                            'filter' => 'type',
                            'op'     => '='
                        ],
                        [
                            'text'   => '免费',
                            'value'  => 'free',
                            'filter' => 'type',
                            'op'     => '='
                        ],
                        [
                            'text'   => '付费',
                            'value'  => 'price',
                            'filter' => 'type',
                            'op'     => '='
                        ],
                        [
                            'text'   => '本地插件',
                            'value'  => 'local',
                            'filter' => 'type',
                            'op'     => '='
                        ]
                    ]
                ]
            ]
        ]
    ];

    public function _initialize()
    {
        parent::_initialize();
        $this->config['field'] = $this->formatField();
        $this->config['pk']    = 'id';
        if (!$this->isSuperAdmin() && in_array($this->request->action(), ['install', 'uninstall', 'local', 'upgrade'])) {
            $this->error(__('Access is allowed only to the super management group'));
        }
    }

    public function index()
    {
        $addons = get_addon_list();
        foreach ($addons as $k => $v) {
            $config   = get_addon_config($v['name']);
            $addons[$k]['config'] = $config ? 1 : 0;
            $addons[$k]['url']    = str_replace($this->request->server('SCRIPT_NAME'), '', $v['url']);
        }
        if ($this->request->isPost()) {
            $params = $this->request->post();
            $params['limit'] = 10;
            $result = [];
            $filter = json_decode($params['filter'], true);
            if (isset($filter['type']) && $filter['type'] === 'local') {
                $this->downloaded();
            }
            $result = Http::get(config('fastadmin.api_url') . '/addon/index', $params);
            if ($result) {
                $result = (array) json_decode($result, true);
                $rows   = isset($result['rows']) ? $result['rows'] : [];
                $total  = isset($result['total']) ? $result['total'] : 0;

                Cache::set('addonCategorys', $result['category'], 600);
                $tabList[]  = array('id' => 'all', 'name' => '全部');
                $tabList    = array_merge($tabList, $result['category']);
                foreach ($rows as $k => $v) {
                    if(isset($addons[$v['name']])) {
                        $rows[$k]['local'] = $addons[$v['name']];
                    }
                }
                foreach ($result['category'] as $k => $v) {
                    $this->config['fieldContent']['category'][] = [
                        $v['id'] => $v['name']
                    ];
                }
                $data = [
                    'tabList'  => $tabList,
                    'dataList' => array('total' => $total, 'rows' => $rows),
                    'config'   => $this->config,
                ];
                $this->success('ok', $data);
            }
        }
    }

    /**
     * 配置
     */
    public function config()
    {
        if ($this->request->isPost()) {
            $name   = $this->request->post('id');
            $field   = $this->request->post('field');
            $value  = $this->request->post('value');
            $config = get_addon_fullconfig($name);
            if ($name && $field) {
                foreach ($config as $k => &$v) {
                    if ($field ===  $v['name']) {
                        if ($v['type'] == 'array') {
                            $value = is_array($value) ? $value : (array) json_decode($value, true);
                            $v['value'] = $value;
                        } else {
                            $v['value'] = is_array($value) ? implode(',', $value) : $value;
                        }
                    }
                }
                try {
                    //更新配置文件
                    set_addon_fullconfig($name, $config);
                    Service::refresh();
                    $this->success();
                } catch (Exception $e) {
                    $this->error(__($e->getMessage()));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        } else {
            $name = $this->request->get('name');
            $config = get_addon_fullconfig($name);
            if (!$name) {
                $this->error(__('Parameter %s can not be empty', 'name'));
            }
            if (!preg_match("/^[a-zA-Z0-9]+$/", $name)) {
                $this->error(__('Addon name incorrect'));
            }
            if (!is_dir(ADDON_PATH . $name)) {
                $this->error(__('Directory not found'));
            }
            $info = get_addon_info($name);
            
            if (!$info) {
                $this->error(__('No Results were found'));
            }
            $tips = [];
            foreach ($config as $index => &$item) {
                if ($item['name'] == '__tips__') {
                    $tips = $item;
                    unset($config[$index]);
                }
            }
            $this->success('ok',['info' => $info, 'config' => $config, 'tips' => $tips]);
        }
    }

    /**
     * 禁用启用
     */
    public function state()
    {
        $name = $this->request->post("name");
        $action = $this->request->post("action");
        $force = (int) $this->request->post("force");
        if (!$name) {
            $this->error(__('Parameter %s can not be empty', 'name'));
        }
        if (!preg_match("/^[a-zA-Z0-9]+$/", $name)) {
            $this->error(__('Addon name incorrect'));
        }
        try {
            $action = $action == 'enable' ? $action : 'disable';
            //调用启用、禁用的方法
            Service::$action($name, $force);
            Cache::rm('__menu__');
            $this->success(__('Operate successful'));
        } catch (AddonException $e) {
            $this->result($e->getData(), $e->getCode(), __($e->getMessage()));
        } catch (Exception $e) {
            $this->error(__($e->getMessage()));
        }
    }

    /**
     * 已装插件
     */
    public function downloaded()
    {
        $offset = (int) $this->request->post('offset');
        $limit  = (int) $this->request->post('limit');
        $filter = $this->request->post('filter');
        $search = $this->request->post('search');
        $search = htmlspecialchars(strip_tags($search));
        $onlineaddons = Cache::get('onlineaddons');
        if (!is_array($onlineaddons) || empty($onlineaddons)) {
            $onlineaddons = [];
            $categoryList = [];
            $result = Http::sendRequest(config('fastadmin.api_url') . '/addon/index');

            if ($result['ret']) {
                $json = (array) json_decode($result['msg'], true);

                $categoryList = isset($json['category']) ? $json['category'] : [];
                $rows = isset($json['rows']) ? $json['rows'] : [];
                foreach ($rows as $index => $row) {
                    $onlineaddons[$row['name']] = $row;
                }
            }
            Cache::set('addonCategorys', $categoryList, 600);
            Cache::set('onlineaddons', $onlineaddons, 600);
        }
        $filter = (array) json_decode($filter, true);
        $addons = get_addon_list();
        $list = [];
        foreach ($addons as $k => $v) {
            if ($search && stripos($v['name'], $search) === false && stripos($v['intro'], $search) === false) {
                continue;
            }

            if (isset($onlineaddons[$v['name']])) {
                $config   = get_addon_config($v['name']);
                $v['config'] = $config ? 1 : 0;
                $v['local'] = $v;
                $v = array_merge($v, $onlineaddons[$v['name']]);
            } else {
                $v['category_id'] = 0;
                $v['flag'] = '';
                $v['banner'] = '';
                $v['image'] = '';
                $v['donateimage'] = '';
                $v['demourl'] = '';
                $v['price'] = __('None');
                $v['screenshots'] = [];
                $v['releaselist'] = [];
            }
            $v['url'] = addon_url($v['name']);
            $v['url'] = str_replace($this->request->server('SCRIPT_NAME'), '', $v['url']);
            $v['createtime'] = filemtime(ADDON_PATH . $v['name']);
            
            if ($filter && isset($filter['category_id']) && is_numeric($filter['category_id']) && $filter['category_id'] != $v['category_id']) {
                continue;
            }
            $list[] = $v;
        }
        $total = count($list);
        if ($limit) {
            $list = array_slice($list, $offset, $limit);
        }
        $addonCategorys = Cache::get('addonCategorys');
        $result    = array('total' => $total, 'rows' => $list);
        $tabList[] = array('id' => 'all', 'name' => '全部');
        $tabList   = array_merge($tabList, $addonCategorys);
        foreach ($addonCategorys as $k => $v) {
            $this->config['fieldContent']['category'][] = [
                $v['id'] => $v['name']
            ];
        }
        $data = [
            'tabList'  => $tabList,
            'dataList' => $result,
            'config'   => $this->config
        ];
        $this->success('ok', $data);
    }
}
